﻿/// <reference path="backbone-min.js" />
/// <reference path="jquery-1.8.3.min.js" />
/// <reference path="underscore-min.js" />
/// <reference path="app.js" />
'use strict';

var Bk = Backbone;
var notifycation = [];
var workingOnIt = '<center><span class="ms-accentText" style=\'font-family: "Segoe UI Light", "Segoe UI", Tahoma, Helvetica, Arial, sans-serif; font-size: 36px;\'>Working on it...</span></center>';

var HeaderView = Bk.View.extend({
    initialize: function () {
        //thi.render();
    },

    render: function () {
        var template = _.template(App.Template.load_template('../Templates/Header.html'));
        $('#header').html(template);
        return this;
    }
});

var EzEditView = Bk.View.extend({
    isReload: false,
    render: function () {
        var template = _.template(workingOnIt);
        $('#ezEdit').html(template);
        if (!App.ViewedLists ||
           !App.ViewedLists.length ||
           App.ViewedLists.length == 0) {
            loadViewdListsProperty(function () {
                
                loadEzEdit(false);
            }, function () { });
        }
        else {
            loadEzEdit(this.isReload);
        }
       
        return this;
    }
});

function ensureListsData(onSuccess,onFail)
{
    if ((!App.ViewedLists ||
           !App.ViewedLists.length ||
           App.ViewedLists.length == 0) ||
        (!viewedLists || viewedLists.length == 0)) {
        loadViewdListsProperty(onSuccess, onFail);
    }
    else {
        if (onSuccess) {
            onSuccess();
        }
    }
}

function loadEzEdit(isReload)
{
    if (isReload || !App.Views[ezEditViewString]) {
        var template = _.template(App.Template.load_template('../Templates/EzEdit.html'));
        App.Views[ezEditViewString] = template;
        showConfigurationTemplate(template);
    }
    else {
        showConfigurationTemplate(App.Views[ezEditViewString]);
    }

    $('panorama .panorama-sections .panorama-section.tile-span-3').css('width', '480px');
    
}

var ViewedListsView = Bk.View.extend({
    render: function () {
        var template = _.template(workingOnIt);
        $('#ezEdit').html(template)
        ensureListsData(mergeAllLists());
        return this;
    }
});

var MainView = Bk.View.extend({
    render: function () {
        App.ensureData(App.createChart);
        return this;
    }
});

var ChartTypeView = Bk.View.extend({
    initialize: function () { App.ChartTypes = new ChartTypesModels(); },
    render: function () {
        App.ChartTypes.isLoaded = false;
        var query = new SP.CamlQuery();
        var web = context.get_web();
        var configurationList = web.get_lists().getByTitle(configurationListName);
        var items = configurationList.getItems(query);
        context.load(items);
        context.executeQueryAsync(function (senader, e) {
            var item = items.get_item(0);
            if (item) {
                var ct = item.get_item(chartTypeFieldName);
                var chartType = JSON.parse(ct);
                App.ChartType = new ChartTypesModel();
                if (chartType && chartType.length > 0) {
                    var chartType = chartType[0];
                    //update model
                    App.ChartTypes.each(function (model) {
                        if (!chartType.chartType) {
                            return;
                        }
                        if (model.get('chartType') == chartType.chartType) {
                            model.set({ selected: true }, { chartType: chartType.chartType });
                            App.ChartType = model;
                        }
                    });
                    App.ChartTypes.sort();
                }
            }
            //load teampate
            App.ChartTypes.isLoaded = true;
            var template = _.template(App.Template.load_template('../Templates/ChartTypes.html'));
            showConfigurationTemplate(template, function () {
                $('.panorama').panorama({
                    nicescroll: false,
                    showscrollbuttons: true,
                    keyboard: true
                });
                $('.panorama-section.tile-span-3').css('width', '280px');
                var index = 0;
                $(".app-chart-type").each(function () {
                    var model = App.ChartTypes.at(index);
                    $(this).on('click', function () { selectChartType(this, model.get('chartType')) });
                    if (model.get('selected')) {
                        $(this).addClass("imgPlate mediumListIconTextItem selected");
                    }
                    else {
                        $(this).addClass("imgPlate mediumListIconTextItem");
                    }
                    index++;
                });
            }); 
        });
        return this;
    }
});

var ChartConfigurationView = Bk.View.extend({
    render: function () {
        var template = _.template(workingOnIt);
        $('#ezEdit').html(template);
        ensureListsData(function () {
            if (!App.ViewedLists ||
            !App.ViewedLists.length ||
            App.ViewedLists.length == 0) {
                if (!App.Views["NoListSelectedError"]) {
                    var template = _.template(App.Template.load_template('../Templates/NoListSelectedError.html'));
                    App.Views["NoListSelectedError"] = template;
                    showConfigurationTemplate(template);
                }
                else {
                    showConfigurationTemplate(App.Views["NoListSelectedError"]);
                }
            }
            else {
                App.ListFields = new ListFields({ listName: App.ViewedLists.at(0).get('listName') });
                var self = this;
                App.ListFields.loadFields(function () {
                    loadConfiguration(function () {
                        var template = _.template(App.Template.load_template('../Templates/Configuration.html'));
                        showConfigurationTemplate(template);
                    });
                    
                }, function () { });

            }
        });
    }
});

var ErrorInEzEditView = Bk.View.extend({
    render: function () {
        if (!App.Views["ErrorInEzEditView"]) {
            var template = _.template(App.Template.load_template('../Templates/ErrorInEzEdit.html'));
            App.Views["ErrorInEzEditView"] = template;
            showConfigurationTemplate(template); 
        }
        else {
            showConfigurationTemplate(App.Views["ErrorInEzEditView"]);
        }
        App.ErrorMessage = null;
    }
});

var ErrorInChartView = Bk.View.extend({
    render: function ()
    {
        var template = _.template(App.Template.load_template('../Templates/ErrorInChart.html'));
        showTemplate($('#content'), template);
        App.ErrorMessage = null;
    }
});

App.Template = {
    load_template: function (url) {
        var data = '';
        $.ajax({
            async: false,
            url: url,
            success: function (response) {
                data = response;
            }
        });
        return data;
    }
};

function showConfigurationTemplate(template, callback)
{
    showTemplate($('#ezEdit'),template, callback);
}

function showTemplate(parent, template, callback)
{
    parent.hide(0, null, function () {
        parent.html(template);
        if (callback) {
            callback();
        }
        parent.show(500);
    });
}

function loadConfiguration(onSuccess)
{
    var query = new SP.CamlQuery();
    var web = context.get_web();
    var configurationList = web.get_lists().getByTitle(configurationListName);
    var items = configurationList.getItems(query);
    context.load(items);
    context.executeQueryAsync(function (senader, e) {
        var item = items.get_item(0);
        if (item) {
            var configuration = item.get_item(chartConfigurationFieldName);
            var configurationObj = JSON.parse(configuration);
            if (configurationObj) {
                if (configurationObj.xAxis) {
                    App.ConfigurationSettings.xAxis.filedName = configurationObj.xAxis.filedName;
                    App.ConfigurationSettings.xAxis.sortName = configurationObj.xAxis.sortName;
                    App.ConfigurationSettings.set({ xAxis: App.ConfigurationSettings.xAxis });
                }
                if (configurationObj.yAxis) {
                    for (var i = 0; i < configurationObj.yAxis.fieldNames.length; i++) {
                        App.ConfigurationSettings.yAxis.fieldNames[i] = configurationObj.yAxis.fieldNames[i];
                        App.ConfigurationSettings.yAxis.aggregateFunction[i] = configurationObj.yAxis.aggregateFunction[i];
                        App.ConfigurationSettings.yAxis.seriesName[i] = configurationObj.yAxis.seriesName[i];
                    }
                    App.ConfigurationSettings.set({ yAxis: App.ConfigurationSettings.yAxis });
                }
            }
        }
        if (onSuccess) {
            onSuccess();
        }
    },
    function (sender, e) {
        App.ErrorMessage = e.get_message();
        App.ErrorInEzEditView.render();
    });
}

function loadViewdListsProperty(onSuccess,onFail) {
    var query = new SP.CamlQuery();
    var web = context.get_web();
    var configurationList = web.get_lists().getByTitle(configurationListName);
    var items = configurationList.getItems(query);
    context.load(items);
    context.executeQueryAsync(function (senader, e) {
        viewedLists.clear();
        var item = items.get_item(0);
        if (item) {
            var viewedList = item.get_item('ViewedLists');
            var lists = JSON.parse(viewedList);
            if (lists) {
                
                //App.ViewedLists.clear();
                for (var i = 0; i < lists.length; i++) {
                    var viewedListModel = new ViewedListsModel();
                    viewedListModel.set({ siteUrl: lists[i].siteUrl });
                    viewedListModel.set({ listName: lists[i].listName });
                    viewedListModel.set({ selected: lists[i].selected });
                    viewedListModel.set({ description: lists[i].description });
                    viewedListModel.set({ itemCount: lists[i].itemCount });
                    viewedListModel.set({ imageUrl: lists[i].imageUrl });
                    viewedLists.add(viewedListModel);
                    var theList = App.ViewedLists.find(function (model) { return model.get('siteUrl') == viewedListModel.get('siteUrl') && model.get('listName') == viewedListModel.get('listName'); });
                    if (!theList) {
                        App.ViewedLists.add(viewedListModel);
                    }
                    else {
                        theList.set({ selected: true });
                        viewedListModel.set({ selected: true });
                    }
                }
            }
        }
        if (onSuccess) onSuccess();
    }, function () {
        if (onFail) {
            onFail();
        }
    });
}

function mergeAllLists() {
    var site = context.get_site();
    var web = site.get_rootWeb();
    context.load(web);
    var lists = web.get_lists();
    context.load(lists);

    var imageUrl = "/_layouts/15/images/ltdl.png?rev=23";
    context.executeQueryAsync(function (sender, e) {
        var enumerator = lists.getEnumerator();
        var siteUrl = web.get_url();
        while (enumerator.moveNext()) {
            var isFound = false;
            var list = enumerator.get_current();
            if (ignoreLists(list)) {
                continue;
            }
            var listName = list.get_title();
            imageUrl = list.get_imageUrl();
            if (imageUrl.indexOf("it") > 0) {
                imageUrl = imageUrl.replace("it", "lt");
            }
            else {
                imageUrl = imageUrl.replace("lt", "it");
            }
            imageUrl = imageUrl.replace("gif", "png");
            var listDescription = list.get_description();
            var itemCount = list.get_itemCount();
            var existedList = App.ViewedLists.find(function (model) {
                return model.get('siteUrl') == siteUrl && model.get('listName') == listName;
            });
            if (!existedList) {
                var viewedListModel = new ViewedListsModel();
                viewedListModel.set({ siteUrl: siteUrl });
                viewedListModel.set({ listName: listName });
                viewedListModel.set({ selected: false });
                viewedListModel.set({ description: listDescription });
                viewedListModel.set({ itemCount: itemCount });
                viewedListModel.set({ imageUrl: imageUrl });
                viewedLists.add(viewedListModel);
            }
            else if (existedList.get('selected')) {
                var theList = viewedLists.find(function (model) { return model.get('siteUrl') == existedList.get('siteUrl') && model.get('listName') == existedList.get('listName'); });
                if (theList) {
                    theList.set({ selected: true });
                }
            }
        }
        createViewedLists();
    }, function () { });
}

function ignoreLists(list)
{
    return list.get_isCatalog() || list.get_baseTemplate() == 112 || list.get_baseTemplate() == 125 || list.get_baseTemplate() == 124 || list.get_baseTemplate() == 122;
}

function createViewedLists() {
    App.ViewedLists.isLoaded=true;
    var template = _.template(App.Template.load_template('../Templates/ViewedLists.html'));

    showConfigurationTemplate(template, function () {
        $('.panorama').panorama({
            nicescroll: false,
            showscrollbuttons: true,
            keyboard: true,
            allowPageScroll: "auto"
        });
        $('.panorama-section.tile-span-3').css('width', '280px');
        var index = 0;
        $(".app-list").each(function () {
            var model = viewedLists.at(index);
            $(this).on("click", function () { selectList(this, model.get('listName'), model.get('siteUrl'), model.get('description'), model.get('itemCount'), model.get('imageUrl')) });
            if (!model.get('selected')) {
                $(this).addClass(" ms-vl-apptile ms-vl-apptilehover mediumListIconTextItem ");
            }
            else {
                $(this).addClass(" ms-vl-apptile ms-vl-apptilehover mediumListIconTextItem selected ");
            }
            index++;
        });
    });
    

}

function selectList(target, listName, siteUrl, description, itemCount, imageUrl)
{
    var theList = App.ViewedLists.find(function (model) {
       return model.get('siteUrl') == siteUrl && model.get('listName') == listName;
    });
    if (theList) {
        var isSelected = false;
        theList.set({ selected: isSelected }, { target: target });
        if (!isSelected) {
            App.ViewedLists.remove(theList);
        }
    }
    else {
        var viewedListModel = new ViewedListsModel();
        viewedListModel.set({ siteUrl: siteUrl });
        viewedListModel.set({ listName: listName });
        viewedListModel.set({ selected: true }, { target: target });
        viewedListModel.set({ description: description });
        viewedListModel.set({ itemCount: itemCount });
        viewedListModel.set({ imageUrl: imageUrl });
        App.ViewedLists.add(viewedListModel);
    }
}

function selectChartType(target, chartType) {
    var theChartType = App.ChartTypes.find(function (model) {
        return model.get('chartType') == chartType;
    });
    if (theChartType) {
        var isSelected = $(target).hasClass("selected");
        if (!isSelected) {
            var index = 0;
            App.ChartTypes.each(function (model) {
                model.set({ selected: false,chartType: model.get('chartType') }, { chartType: model.get('chartType') });
            });
            theChartType.set({ selected: !isSelected, chartType: chartType }, { chartType: chartType });
        }
    }
}

function updateViewedListsSettings() {
    disableSave();
    App.ViewedLists.save(onSuccess, onFail);
}

function updateConfigurationSettings()
{
    disableSave();
    App.ConfigurationSettings.save(onSuccess, onFail);
}

function disableSave()
{
    $('#saveCommand').attr('disabled', 'disabled');
}

function enableSave()
{
    $('#saveCommand').removeAttr('disabled');
}

function getConfiguredChartType()
{
    var chartTypes = new ChartTypesModels({ isInitialize: false });
    App.ChartTypes.each(function (model) {
        if (model.get('selected') === true) {
            chartTypes.add(model);
        }
    });
    return chartTypes;
}

function onSuccess() {
    enableSave();
    clearNotifycation();
    showNotifycation("Save success...");
}

function onFail(sender, e) {
    enableSave();
    clearNotifycation();
    showNotifycation("Save fail...");
}

function updateChartTypeSettings() {
    disableSave();
    var chartTypes = getConfiguredChartType();
    chartTypes.save(onSuccess, onFail);
}

function showNotifycation(message)
{
    notifycation.push(SP.UI.Notify.addNotification(message));
}

function clearNotifycation()
{
    for (var i = 0; i < notifycation.length; i++) {
        SP.UI.Notify.removeNotification(notifycation[i]);
    }
}







